<template>
  <BaseDialog
    v-model="dialogVisible"
    :title="$t('push.addSession')"
    width="550px"
    :before-close="handleClose"
  >
    <el-form
      ref="refDialogForm"
      v-loading="formLoading"
      class="set-dialog-form"
      :label-width="language === 'en' ? '180px' : '80px'"
      :model="formData"
      :rules="rules"
    >
      <el-form-item :label="$t('fleet.customerName')" prop="customerId">
        <el-select
          v-model="formData.customerId"
          :placeholder="
            g_rules.zhAndEnShowMsg(
              g_t('public.pleaseSelect'),
              $t('fleet.customerName')
            )
          "
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="form-dialog-footer">
        <el-button plain @click="handleClose">{{
          $t('public.cancel')
        }}</el-button>
        <el-button type="primary" @click="handleSubmitForm">{{
          $t('public.confirm')
        }}</el-button>
      </div>
    </template>
  </BaseDialog>
</template>

<script setup>
const emit = defineEmits(['update'])
const dialogVisible = defineModel({
  type: Boolean,
  default: false
})
const { language } = storeToRefs(useAppStore())
const { userInfo } = storeToRefs(useUserStore())

const refDialogForm = ref(null)
const formLoading = ref(false)
const options = ref([])
const formData = ref({
  customerId: ''
})
const rules = {
  customerId: g_rules.selectRule(g_t('fleet.customerName'))
}

onMounted(() => {
  getOptions()
})

// 查询下拉列表
const getOptions = () => {
  formLoading.value = true
  g_api.userCenter
    .apiChatTenantList()
    .then(({ code, data }) => {
      if (code === '200' && data) {
        options.value = data
      }
    })
    .finally(_ => {
      formLoading.value = false
    })
}

const handleClose = _ => {
  dialogVisible.value = false
}

const handleSubmitForm = () => {
  if (formLoading.value) return
  refDialogForm.value.validate(valid => {
    console.log('formData.value', formData.value)
    if (!valid) return
    formLoading.value = true
    g_api.sysMsg
      .apiDialogCreate({
        fromId: userInfo.value.userId,
        toTenantId: formData.value.customerId,
        type: 'group'
      })
      .then(res => {
        if (res.code === '200') {
          ElMessage({
            message: res.message,
            type: 'success'
          })
          handleClose()
          emit('update')
        }
      })
      .finally(() => {
        formLoading.value = false
      })
  })
}
</script>

<style scoped lang="scss"></style>
